package eu.flatworld.android.ontop;

import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
import android.view.WindowManager;
import android.widget.Adapter;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockListActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.j256.ormlite.android.apptools.OpenHelperManager;

import eu.flatworld.android.ontop.db.ChecklistItem;
import eu.flatworld.android.ontop.db.DatabaseHelper;
import eu.flatworld.android.ontop.db.Memo;
import eu.flatworld.android.ontop.db.Util;

public class OnTopChecklistActivity extends SherlockListActivity {
	static int MENU_ADD_ID = 1;
	static int MENU_SWITCH_ID = 2;
	static int MENU_SETTINGS_ID = 3;

	private DatabaseHelper dbh = null;
	
	Memo currentMemo =  null;	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Log.d(Main.LOGTAG, "create checklist activity");
		super.onCreate(savedInstanceState);
		registerForContextMenu(this.getListView());

		ActionBar bar = getSupportActionBar();
		bar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
		bar.setDisplayShowTitleEnabled(true);
		bar.setDisplayShowHomeEnabled(true);		
		
		if (MainService.RUNNING) {
			getWindow().addFlags(
					WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
		} else {
			getWindow().clearFlags(
					WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
		}

		if(savedInstanceState == null) {
			if(getIntent() != null && getIntent().getExtras() != null) {
				currentMemo = (Memo)getIntent().getExtras().get("memo");				
			} 		
		} else {
			currentMemo = (Memo)savedInstanceState.get("memo");
		}
		
		if(currentMemo != null) {
			Toast.makeText(this,
					"Got memo: " + currentMemo,
					Toast.LENGTH_SHORT).show();			
			bar.setSubtitle(currentMemo.getName());
		}
		
		loadChecklistItemList(currentMemo);
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putSerializable("memo", currentMemo);
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		if (dbh != null) {
			OpenHelperManager.releaseHelper();
			dbh = null;
		}
	}

	ChecklistItem createCheclistItem(Memo memo, String name) {
		try {
			return Util.createCheclistItem(getDbHelper(), memo, name);
		} catch (java.sql.SQLException ex) {
			String s = getString(R.string.error_creating_the_item);
			Toast.makeText(this, s, Toast.LENGTH_LONG).show();
			Log.e(Main.LOGTAG, s, ex);
		}
		return null;
	}

	void deleteChecklistItem(ChecklistItem ci) {
		try {
			Util.deleteChecklistItem(getDbHelper(), ci);
		} catch (java.sql.SQLException ex) {
			String s = getString(R.string.error_deleting_the_item);
			Toast.makeText(this, s, Toast.LENGTH_LONG).show();
			Log.e(Main.LOGTAG, s, ex);
		}
	}

	void loadChecklistItemList(Memo memo) {
		try {
			List<ChecklistItem> lm = Util.loadChecklistItemList(getDbHelper(), memo);			
			ChecklistItemAdapter adapter = new ChecklistItemAdapter(this, lm);
			setListAdapter(adapter);
		} catch (java.sql.SQLException ex) {
			String s = getString(R.string.error_loading_the_items);
			Toast.makeText(this, s, Toast.LENGTH_LONG).show();
			Log.e(Main.LOGTAG, s, ex);
		}
	}

	private DatabaseHelper getDbHelper() {
		if (dbh == null) {
			dbh = OpenHelperManager.getHelper(this, DatabaseHelper.class);
		}
		return dbh;
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (MainService.RUNNING) {
			getWindow().addFlags(
					WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
		} else {
			getWindow().clearFlags(
					WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
		}
		getSherlock().dispatchInvalidateOptionsMenu();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(Menu.NONE, MENU_ADD_ID, Menu.FIRST + 1, R.string.add)
				.setIcon(android.R.drawable.ic_menu_add)
				.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
		menu.add(Menu.NONE, MENU_SETTINGS_ID, Menu.FIRST + 2, R.string.settings)
				.setIcon(android.R.drawable.ic_menu_preferences)
				.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
		int icon = MainService.RUNNING ? R.drawable.ic_action_switchon
				: R.drawable.ic_action_switchoff;
		menu.add(Menu.NONE, MENU_SWITCH_ID, Menu.FIRST, "Switch").setIcon(icon)
				.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
		return true;
	}
	
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		int icon = MainService.RUNNING ? R.drawable.ic_action_switchon
				: R.drawable.ic_action_switchoff;
		menu.findItem(MENU_SWITCH_ID).setIcon(icon);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// This uses the imported MenuItem from ActionBarSherlock
		if (item.getItemId() == MENU_SWITCH_ID) {
			if (!MainService.RUNNING) {
				Log.d(Main.LOGTAG, getString(R.string.ontop_activated));
				Intent i = new Intent();
				i.setClassName("eu.flatworld.android.ontop",
						"eu.flatworld.android.ontop.MainService");
				startService(i);
				Toast.makeText(this, R.string.ontop_activated, Toast.LENGTH_SHORT)
						.show();
				item.setIcon(R.drawable.ic_action_switchon);
				getWindow().addFlags(
						WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
			} else {
				Log.d(Main.LOGTAG, getString(R.string.ontop_deactivated));
				Intent i = new Intent();
				i.setClassName("eu.flatworld.android.ontop",
						"eu.flatworld.android.ontop.MainService");
				stopService(i);
				Toast.makeText(this, R.string.ontop_deactivated, Toast.LENGTH_SHORT)
						.show();
				item.setIcon(R.drawable.ic_action_switchoff);

				KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
				if (!km.inKeyguardRestrictedInputMode()) {
					getWindow().clearFlags(
							WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
				}
			}
			return true;
		}
		if (item.getItemId() == MENU_ADD_ID) {
			final AlertDialog.Builder alert = new AlertDialog.Builder(this);
			alert.setTitle(R.string.enter_item_name_);
			// Set an EditText view to get user input
			final EditText input = new EditText(this);
			alert.setView(input);
			alert.setPositiveButton(R.string.ok,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							String value = input.getText().toString();
							if(value.trim().length() == 0) {
								value = getString(R.string.no_name);
							}
							ChecklistItem ci = createCheclistItem(currentMemo, value);
							loadChecklistItemList(currentMemo);							
							return;
						}
					});
			alert.setNegativeButton(R.string.cancel,
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							return;
						}
					});
			final Dialog d = alert.create();
			input.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			    @Override
			    public void onFocusChange(View v, boolean hasFocus) {
			        if (hasFocus) {
			            d.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
			        }
			    }
			});
			d.show();
			return true;
		}

		//Toast.makeText(this, "Got click: " + item.toString(), Toast.LENGTH_SHORT).show();
		return true;
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);

		ChecklistItemAdapter cia = (ChecklistItemAdapter) getListAdapter();
		ChecklistItem ci = cia.getItem(position);
		ci.setChecked(!ci.isChecked());
		cia.notifyDataSetChanged();
		try {
			Util.update(getDbHelper(), ci);
		} catch (java.sql.SQLException ex) {
			String s = getString(R.string.error_updating_item);
			Toast.makeText(this, s, Toast.LENGTH_LONG).show();
			Log.e(Main.LOGTAG, s, ex);
		}
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);

		menu.clear();
		// menu.setHeaderIcon(R.drawable.icon);
		// menu.setHeaderTitle(R.string.options);

		AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
		int position = info.position;
		Adapter adapter = ((ListView) v).getAdapter();
		ChecklistItem ci = (ChecklistItem) adapter.getItem(position);
		menu.setHeaderTitle(ci.getName());
		menu.add(R.string.delete);
	}

	@Override
	public boolean onContextItemSelected(android.view.MenuItem item) {
		// Recupera l'oggetto associato alla lista
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		ChecklistItem ci = (ChecklistItem) getListAdapter().getItem(info.position);
		deleteChecklistItem(ci);
		loadChecklistItemList(currentMemo);
		return true;
	}	
}